var app = angular.module("app", [])
.controller("DemoCtrl", function($http) {
  var vm = this;
  vm.width  = 100;
  vm.height = 100;
  vm.formData = {
    title: 'test',
    titleImage: 'images/test.jpg',
    options: [
      {image: 'images/test.jpg'},
      {image: 'images/test.jpg'}
    ]
  }

  vm.change = function(newImage) {
    console.log(newImage);
    let fd = new FormData();
    fd.append('file', file);
    $http.post('upload.php', fd)
    .then((response) => {
        if (response.data.isSuccess) {
            scope.newImage = response.data.file;
        }
    })
  }
})

app.directive('imagePreview', function($http) {
  return {
    restrict: "AE",
    scope: {
      previewWidth :'@',
      previewHeight:'@',
      newImage     :'=',
      onChange: '&'
    },
    template: `<div><button ng-click="del()">Del</button><input type="file" class="fileInput" accept="image/*"><div class="imagePreviewWrap"></div></div>`,

    link: (scope, element, attr) => {
      let fileElement = element.find('input:file'), imagePreviewWrap = element.find('.imagePreviewWrap');
      if (typeof FileReader === 'undefined') {
        errorConsole('your browser do not support FileReader');
      }else {
        fileElement.on("change", function() {
          let file = this.files[0], reader = new FileReader(), 
          width = parseInt(scope.previewWidth) || 200, height = parseInt(scope.previewHeight) || 200;
          reader.readAsDataURL(file); 
          // read success
          reader.onload = function(e){

            imagePreviewWrap.html(`<img src=${reader.result} width="${width}" height=${height} alt=""/>`);


            scope.onChange();
             // upload image

              let fd = new FormData();
              fd.append('file', file);
              $http.post('upload.php', fd)
              .then((response) => {
                  if (response.data.isSuccess) {
                      scope.newImage = response.data.file;
                  }
              })

          }
          reader.onerror = function(e){ 
            errorConsole('read file error, please check the file type');
          } 
        })
      }

      scope.del = function() {
        imagePreviewWrap.html("");
        scope.newImage = "";
      }

      function errorConsole(message) {
        console.error(`imagePreviewDirective: ${message}`)
      }

      scope.$watch('previewWidth', (newValue, oldValue) => {
        //console.log(newValue +'-'+oldValue);
      })
    }
  };
});